package com.bamboo.eduservice.service.impl;

import com.bamboo.eduservice.entity.EduChapter;
import com.bamboo.eduservice.entity.EduVideo;
import com.bamboo.eduservice.entity.vo.ChapterVo;
import com.bamboo.eduservice.entity.vo.VideoVo;
import com.bamboo.eduservice.mapper.EduChapterMapper;
import com.bamboo.eduservice.service.EduChapterService;
import com.bamboo.eduservice.service.EduVideoService;
import com.bamboo.servicebase.exceptionhandler.BambooException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author jack.wu
 * @since 2020-07-05
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {


    @Resource
    private EduVideoService videoService;

    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {

        List<ChapterVo> result = new ArrayList<>(10);
        // 获取章节
        QueryWrapper<EduChapter> chapterWrapper = new QueryWrapper<>();
        chapterWrapper.eq("course_id", courseId);
        List<EduChapter> chapterList = baseMapper.selectList(chapterWrapper);
        // 获取小节
        QueryWrapper<EduVideo> videoWrapper = new QueryWrapper<>();
        videoWrapper.eq("course_id", courseId);
        List<EduVideo> videoList = videoService.list(videoWrapper);
        for (EduChapter chapter : chapterList) {
            // 封装章节
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter, chapterVo);
            result.add(chapterVo);
            // 封装小节
            List<VideoVo> videoVoList = new ArrayList<>(10);
            for (EduVideo video : videoList) {
                if (video.getChapterId().equals(chapter.getId())) {
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video, videoVo);
                    videoVoList.add(videoVo);
                }
            }
            chapterVo.setVideoVoList(videoVoList);
        }

        return result;
    }

    @Override
    public boolean deleteChapterInfo(String id) {
        QueryWrapper<EduVideo> videoWrapper = new QueryWrapper<>();
        videoWrapper.eq("chapter_id", id);
        int count = videoService.count(videoWrapper);
        if (count > 0) {
            throw new BambooException(20001, "请先删除小节");
        }
        int delete = baseMapper.deleteById(id);
        return delete > 0;
    }
}
